#include "StdAfx.h"
#include "sourceimage.h"
#include "windowsx.h"

CSourceImage::CSourceImage(void)
{
	m_valid=FALSE;
}

CSourceImage::~CSourceImage(void)
{
}

BYTE* CSourceImage::GetData(void)
{
	return m_pData;
	
}

BOOL CSourceImage::IsValid(void)
{
	return m_valid;
}

char* CSourceImage::GetFileName(void)
{
	return m_FileName;
}

BOOL CSourceImage::CreateHBitmap(void)
{
	CClientDC dc(NULL);
	hBitmap=CreateDIBitmap (dc.GetSafeHdc(),
		                   (LPBITMAPINFOHEADER)m_pBitmapInfo,
		                   (DWORD)CBM_INIT,
		                   m_pData,
		                   (LPBITMAPINFO)m_pBitmapInfo,
		                   DIB_RGB_COLORS);
	   return TRUE;
}

UINT CSourceImage::GetWidth(void)
{
	return (UINT)m_pBitmapInfoHeader->biWidth;
}

UINT CSourceImage::GetHeight(void)
{
	return (UINT)m_pBitmapInfoHeader->biHeight;
}

DWORD CSourceImage::GetSize(void)
{
	if(m_pBitmapInfoHeader->biSizeImage!=0)
		return m_pBitmapInfoHeader->biSizeImage;
	else
	{
		DWORD height=(DWORD)GetHeight();
		DWORD width=(DWORD)GetWidth();
		return height*width;
	}
}

UINT CSourceImage::GetNumberofColors(void)
{
	int numberOfColors;
	if ((m_pBitmapInfoHeader->biClrUsed==0)&&(m_pBitmapInfoHeader->biBitCount<9))
	{
		switch(m_pBitmapInfoHeader->biBitCount)
		{
		case 1:numberOfColors=2;break;
		case 4:numberOfColors=16;break;
        case 8:numberOfColors=256;
		}
	}
	else
		numberOfColors=(int)m_pBitmapInfoHeader->biClrUsed;
	return numberOfColors;
}



void CSourceImage::LoadFile(const char* DibFileName)
{
	strcpy(m_FileName,DibFileName);
	CFile DibFile(m_FileName,CFile::modeRead);
	DibFile.Read((void*)&m_BitmapFileHeader,sizeof(BITMAPFILEHEADER));
	if(m_BitmapFileHeader.bfType==0x4d42)
	{
		DWORD FileLength=DibFile.GetLength();
		m_dSize=FileLength-sizeof(BITMAPFILEHEADER);
		m_pDib=(BYTE*)GlobalAllocPtr(GMEM_MOVEABLE,m_dSize);
		DibFile.Read((void*)m_pDib,m_dSize);
		DibFile.Close();
		m_pBitmapInfo=(BITMAPINFO*)m_pDib;
		m_pBitmapInfoHeader=(BITMAPINFOHEADER*)m_pDib;
		m_pRGB=(RGBQUAD*)(m_pDib+m_pBitmapInfoHeader->biSize);
		int m_numberOfColors=GetNumberofColors();
		if(m_pBitmapInfoHeader->biClrUsed==0)
		{
			m_pBitmapInfoHeader->biClrUsed=m_numberOfColors;
		}
		DWORD colorTableSize=m_numberOfColors*sizeof(RGBQUAD);
		m_pData=m_pDib+m_pBitmapInfoHeader->biSize+colorTableSize;
		if(m_pRGB==(RGBQUAD*)m_pData )// No Color Table
		{
			m_pRGB=NULL;
		}
		m_pBitmapInfoHeader->biSizeImage=GetSize();
		m_valid=TRUE;
	}
	else
	{
		m_valid=FALSE;
		AfxMessageBox("This is not a bitmap file!");
	}

}
